import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { startOfMonth, format, subMonths, isWithinInterval } from 'date-fns';
import { zhCN } from 'date-fns/locale';

export async function GET() {
  try {
    // 获取所有支出记录
    const expenses = await prisma.expense.findMany({
      select: {
        type: true,
        amount: true,
        paymentDate: true,
      },
      orderBy: {
        paymentDate: 'asc',
      },
    });

    // 获取最近12个月的数据
    const today = new Date();
    const monthsRange = Array.from({ length: 12 }, (_, i) => {
      const date = subMonths(today, i);
      return {
        start: startOfMonth(date),
        label: format(date, 'yyyy年MM月', { locale: zhCN }),
      };
    }).reverse();

    // 按月份统计支出
    const monthlyExpenses = monthsRange.reduce<MonthlyExpense[]>((acc, { start, label }) => {
      const endDate = new Date(start.getFullYear(), start.getMonth() + 1, 0);
      
      const monthExpenses = expenses.filter(expense => 
        isWithinInterval(expense.paymentDate, { start, end: endDate })
      );

      const expensesByType = monthExpenses.reduce((typeAcc, expense) => {
        typeAcc[expense.type] = (typeAcc[expense.type] || 0) + expense.amount;
        return typeAcc;
      }, {} as Record<string, number>);

      const monthTotal = Object.values(expensesByType).reduce((a, b) => a + b, 0);

      acc.push({
        month: label,
        total: monthTotal,
        material: expensesByType.material || 0,
        labor: expensesByType.labor || 0,
        equipment: expensesByType.equipment || 0,
        other: expensesByType.other || 0,
        accumulated: (acc[acc.length - 1]?.accumulated || 0) + monthTotal,
      });

      return acc;
    }, []);

    return NextResponse.json(monthlyExpenses);
  } catch (error) {
    console.error('获取支出趋势数据失败:', error);
    return NextResponse.json(
      { error: '获取支出趋势数据失败' },
      { status: 500 }
    );
  }
}

interface MonthlyExpense {
  month: string;
  total: number;
  material: number;
  labor: number;
  equipment: number;
  other: number;
  accumulated: number;
} 